<template>
    <LoadPage :show="show" />
  <nut-notify  v-model:visible="noticeShow" msg="点击左侧分享按钮邀请好友得佣金" background="#fb4e47"/>
    <view class="main" v-if="JSON.stringify(detail) != '{}'">
        <view class="swiper">
            <nut-swiper :init-page="current" auto-play="3000" :loop="true" @change="index => current = index">
                <nut-swiper-item v-for="item in detail.image.split(',')" :key="item">
                    <image :src="item" mode="aspectFill" />
                </nut-swiper-item>
                <template v-slot:page>
                    <div class="page dispaly-align-center"> {{ current }}/{{ detail.image.split(',').length }} </div>
                </template>
            </nut-swiper>
        </view>
        <view class="con">
            <view class="desc">
                <view class="title">{{ detail.name }}</view>
                <view class="op-left dispaly-center">
                    <nut-price :price="detail.money" :decimal-digits="2" :thousands="true" size="large" />
                    <nut-price :price="detail.oldMoney" :decimal-digits="2" :thousands="true" strike-through
                        size="small" />
                </view>
                <view class="tip dispaly-center">
                    <view class="tip-item">已售{{ detail.sales || 0 }}</view>
                </view>
            </view>
            <view class="desc dispaly-just-between server" @click="showBottom = true">
                <view class="d-left dispaly-center">
                    <view class="d-title">服务点</view>
                    <view class="d-name" v-if="defaultAddress.length">{{ defaultAddress[0].name }}</view>
                </view>
                <view class="d-right">
                    <nut-icon size="10" custom-color="#7b7b7b" name="rect-right"></nut-icon>
                </view>
            </view>
            <view class="f-text" v-if="detail.flows">
                <view class=" dispaly-col-center">
                    <view class="line-box  ">
                        <view class="line"></view>
                        <view class="text">流程介绍</view>
                        <view class="line"></view>
                    </view>

                </view>
                <view class="f-con ">
                    <nut-steps direction="vertical">
                        <nut-step v-for="item in detail.flows" :key="item.id" :title="item.name">1</nut-step>
                    </nut-steps>
                </view>
            </view>
            <view class="f-text dispaly-col-center">
                <view class="line-box">
                    <view class="line"></view>
                    <view class="text">图文介绍</view>
                    <view class="line"></view>
                </view>
                <view class="f-con">
                    <rich-text :nodes="detail.intro"></rich-text>
                </view>
            </view>
        </view>
    </view>
    <view class="option-btn-box ">
        <view class="dispaly-just-between op">
            <view class="option dispaly-center ">
                <button open-type="contact" class="o-item  dispaly-col-center">
                    <view class="icon">
                        <nut-icon size="15" custom-color="#7b7b7b" name="dongdong"></nut-icon>
                    </view>
                    <view class="o-name k-name">客服</view>
                </button>
                <view class="o-item  dispaly-col-center" @click="postCollect">
                    <view class="icon">
                        <nut-icon size="15" :custom-color="detail.isCollect == 1 ? '#e85b50' : '#7b7b7b'"
                            name="star-fill-n"></nut-icon>
                    </view>
                    <view class="o-name">{{ detail.isCollect == 1 ? '已收藏' : '收藏' }}</view>
                </view>
            </view>
            <view class="btns dispaly-center">
                <!-- <view class="btn-item add dispaly-align-center" @click="skuShow = true">加入购物车</view> -->
                <view class="btn-item buy dispaly-align-center" @click="buyPayment">立即购买</view>
            </view>
        </view>
    </view>
    <SkuPop :show="skuShow" @close="bool => skuShow = bool" @buy="buy" :data="detail.specNames" :name="detail.name"
        :m="detail.money" />
    <Option @show="bool => showO = bool" @h="h => hb = h" :id="detail.id" />
    <!-- <hbCom :showO="showO" :hb="hb" @close="show => showO = show" /> -->
    <!-- 选择服务点 -->
    <nut-popup position="bottom" :custom-style="{ height: 'auto' }" round v-model:visible="showBottom">
        <nut-picker :field-names="fieldNames" three-dimensional @cancel="showBottom = false" :columns="columns"
            title="选择服务点" @confirm="onConfirm"></nut-picker>
    </nut-popup>

    <nut-overlay v-model:visible="showO" z-index="9999" :close-on-click-overlay="false">
        <view class="wrapper" v-if="JSON.stringify(detail) != '{}'"
            style="display: flex;flex-direction: column;align-items: center;justify-content: center;height: 100%;">
            <view class="c" @click="showO = false" v-if="showO">
                <image src="/static/icon/c.png" />
            </view>
            <nut-button v-if="!showHB" custom-color="#d76457" :loading="!showHB" type="success">海报加载中{{ progressNum }}
                %</nut-button>
            <l-painter @progress="progress" ref="painter" v-if="showO" css="height:818rpx;width:512rpx">
                <l-painter-view css=" width: 750rpx;height: 100%;">
                    <l-painter-image :src="detail.image.split(',')[0]"
                        css="width: 512rpx;height: 512rpx;borderTopLeftRadius: 20rpx;borderTopRightRadius: 20rpx;object-fit: cover;" />
                    <l-painter-view
                        css="background: #fff;width: 512rpx; height: 306rpx;borderBottomLeftRadius:20rpx;borderBottomRightRadius:20rpx">
                        <l-painter-image :src="userInfo.avatar"
                            css="height: 68rpx;width:68rpx;borderRadius:50%;marginTop:20rpx;marginBottom:20rpx;marginLeft: 10rpx;object-fit: cover;" />
                        <l-painter-text :text="userInfo.nickName" css="height: 68rpx;margin:20rpx" />
                        <l-painter-text text="为你推荐"
                            css="height: 68rpx;marginTop:20rpx;marginBottom:20rpx;marginLeft: 10rpx;fontSize:22rpx;color:#999999" />
                        <l-painter-view css="width: 512rpx;">
                            <l-painter-text :text="detail.name" css="marginLeft: 10rpx;fontSize:22rpx;color:#999999" />
                        </l-painter-view>
                        <l-painter-view css="width: 512rpx;height: 68rpx;lineHeight:68rpx;marginTop:30rpx">
                            <l-painter-text :text="'¥' + detail.money"
                                css="marginLeft: 10rpx;fontSize:38rpx;color:#FB4E47" />
                            <!--     position: fixed; -->
                            <l-painter-text :text="'¥' + detail.oldMoney"
                                css="marginLeft: 10rpx;fontSize:24rpx;color:#999999" />
                            <l-painter-image :src="hb"
                                css="height: 110rpx;width:110rpx;position:fixed;bottom:20rpx;right:20rpx" />
                        </l-painter-view>
                    </l-painter-view>
                </l-painter-view>
            </l-painter>
            <view v-if="showO && showHB" class="save dispaly-align-center" @click="sava()">保存图片</view>
        </view>
    </nut-overlay>

    <nut-popup position="bottom" round :custom-style="{ height: 'auto' }" v-model:visible="proxyShow">
        <view class="t">下单协议</view>

        <view class="p">
            <scroll-view scroll-y="true" class="scroll-Y">
                <rich-text :nodes="p"></rich-text>
            </scroll-view>
        </view>
        <view class="btn">
            <view class="bt">
                <nut-button block type="primary" @click="proxyShow = false">拒绝</nut-button>
            </view>
            <view class="bt">
                <nut-button block type="info" @click="proConfirm">同意</nut-button>
            </view>
        </view>
    </nut-popup>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue';
import Option from '@/components/option/option.vue';
import SkuPop from '@/components/sku/skuPop.vue';
import { onShareAppMessage, onShareTimeline, onLoad } from '@dcloudio/uni-app';
import { getServerDetail, serverPointList, collect, serHb, proxy } from '@/api/apiList'
import { saveImage } from '@/utils/util'

// 选择服务点
const showBottom = ref(false)
const columns = ref([
]);
const fieldNames = ref({
    text: "name",
    value: "id",
});
let defaultAddress = ref([])
const getList = async () => {
    const res = await serverPointList()
    if (res.code == 200) {
        columns.value = res.data
        defaultAddress.value = columns.value.filter(item => item.isDefault == 1)
    }
}

// 获取案例详情
let noticeShow  = ref('true')
let hb = ref('')
let userInfo = uni.getStorageSync('user')
let show = ref(true)
const detail = ref({})
const getDetail = async () => {
    await nextTick(async () => {
      const res = await getServerDetail(id.value)
      if (res.code == 200) {
        detail.value = res.data
        detail.value.intro = detail.value.intro.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
            .replace(/<p>/ig, '<p style="font-size: 15px; line-height: 25px;">')
            .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
            .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
            .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
            .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
            .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img style="width: 100%;" $1');
        show.value = false
      }
    })
}

const onConfirm = (event) => {
    defaultAddress.value = [event.selectedOptions[0]]
    // defaultAddress.value = columns.value.filter(item => item.id == event.selectedOptions[0])
    showBottom.value = false
}

// 收藏
const postCollect = async () => {
    const res = await collect({ serviceId: detail.value.id })
    if (res.code == 200) {
        getDetail()
    }
}


const current = ref(1)

// 获取下单协议
const p = ref('')
const getProxy = async () => {
    const res = await proxy('merchant')
    if (res.code == 200) {
        p.value = res.msg
    }
}
// 同意协议后买
const proxyShow = ref(false)
const buyPayment = () => {
    proxyShow.value = true
    getProxy()
}

const proConfirm = () => {
    proxyShow.value = false
    skuShow.value = true
}

// 购买
const skuShow = ref(false)
const buy = (data) => {
    console.log(defaultAddress.value, 'defaultAddress.value')
    if (!defaultAddress.value.length) {
        uni.showToast({ title: '没有服务点', icon: 'none' })
    } else {
        let createOrderData = {
            serviceId: detail.value.id,
            num: data.number,
            specName: data.spec,
            addrId: defaultAddress.value[0].id
        }
        uni.navigateTo({
            url: `/subPackage/server/oerderConfirm?data=${encodeURIComponent(JSON.stringify(createOrderData))}`
        })
        console.log(createOrderData, 'data')
    }

}


let showO = ref(false)

// 保存海报
const painter = ref(null)
const sava = () => {
    nextTick(() => {
        painter.value.canvasToTempFilePathSync({
            fileType: "png",
            // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
            pathType: 'base64',
            quality: 1,
            success: (res) => {
                saveImage(res.tempFilePath)
            },
        })
    })
}

let progressNum = ref(0)
let showHB = ref(false)
const progress = (data) => {
    progressNum.value = parseInt((data * 100))
    showHB.value = data == 1 ? true : false
}

onShareAppMessage(() => {
    return {
        path: `/subPackage/server/serverDetail?id=${detail.value.id}&userId=${userInfo.userId}`,
        imageUrl: detail.value.image.split(',')[0],
        title: detail.value.name
    };
});

onShareTimeline(() => {
    return {
        path: `/subPackage/server/serverDetail?id=${detail.value.id}&userId=${userInfo.userId}`,
        imageUrl: detail.value.image.split(',')[0],
        title: detail.value.name
    };
});



let id = ref('')
onLoad(async (option) => {
    id.value = option.id
    console.log(option, 'opopop')
    if (option.scene || (option.id && option.userId)) {
        let opData = decodeURIComponent(option.scene).split('&') || ''
        let userId = option.userId || opData[0].split('=')[1]
        let sId = option.id || opData[1].split('=')[1]
        id.value = sId
        uni.showModal({
            title: "提示",
            content: "登录加入团队",
            success: function (res) {
                if (res.confirm) {
                    uni.navigateTo({
                        url: `/subPackage/mine/login?userId=${userId}&isL=1`,
                    });
                }
            },
        });
    }
    await getDetail()
    getList()
    // getSerHb()
})
</script>
<style lang="scss" scoped>
:deep(.nut-price--strike) {
    color: #999999;
    margin-left: 20rpx;
}

button {
    padding: 0;
    margin: 0;
    background-color: transparent;
}

button::after {
    border: none;
}

.p {
    display: flex;
    justify-content: center;
    padding: 20rpx;
    max-height: 500rpx;
    height: 500rpx;
    padding-bottom: 100rpx;

    .scroll-Y {
        max-height: 500rpx;
        height: 500rpx;
        padding-bottom: 100rpx;
    }


}

.t {
    color: #999;
    text-align: center;
    margin: 20rpx 0;
}

.btn {
    position: fixed;
    bottom: 0rpx;
    display: flex;
    align-items: center;
    width: 100%;
    background-color: #fff;
    justify-content: center;
    height: 100rpx;

    .bt {
        margin: 0 20rpx;
    }
}

:deep(.nut-button) {
    width: 300rpx;
}

:deep(p) {
    font-size: 20rpx !important;
    color: #777777 !important;
}


.main {
    padding-bottom: 198rpx;

    .con {
        padding: 30rpx;

        .server {
            margin-top: 20rpx;
        }

        .desc {
            background: #FFFFFF;
            border-radius: 12rpx;
            padding: 24rpx 24rpx 24rpx 24rpx;

            .d-left {
                .d-title {
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 26rpx;
                    color: #999999;
                    margin-right: 30rpx;
                }

                .d-name {
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 26rpx;
                    color: #222222;
                }

            }

            .title {
                font-family: PingFang-SC, PingFang-SC;
                font-weight: 500;
                font-size: 32rpx;
                color: #111111;
                margin: 20rpx 0;
            }

            .tip {
                .tip-item:last-child {
                    padding-right: 0;
                    border: none;
                    margin-right: 0;
                }

                .tip-item {
                    margin-right: 10rpx;
                    border-right: 1rpx solid #999;
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 24rpx;
                    color: #999999;
                    padding-right: 14rpx;
                }
            }
        }
    }

    .f-text {
        background: #FFFFFF;
        border-radius: 12rpx;
        padding: 46rpx;
        margin-top: 20rpx;

        .line-box {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .text {
            text-align: center;
            font-family: PingFang-SC, PingFang-SC;
            font-weight: 500;
            font-size: 26rpx;
            color: #333333;
            padding: 0 20rpx;
        }

        .line {
            width: 100rpx;
            height: 1px;
            background-color: #ccc;
        }

    }

    .swiper {
        image {
            width: 750rpx;
            height: 750rpx;
        }

        .page {
            width: 56rpx;
            height: 40rpx;
            background: #000000;
            border-radius: 20rpx;
            opacity: 0.5;

            position: absolute;
            bottom: 20rpx;
            right: 20rpx;
            text-align: center;
            color: #fff;
            font-size: 14px;
        }
    }
}

.option-btn-box {
    z-index: 99;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 178rpx;
    background: #FFFFFF;
    padding: 25rpx 66rpx 0 66rpx;

    .op {
        width: 100%;

        .option {
            flex: 2;

            .o-item:first-child {
                margin-right: 70rpx;
            }

            .o-item {
                .o-name {
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 22rpx;
                    color: #777777;
                }

                .k-name {
                    margin-top: -35rpx;
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 22rpx;
                    color: #777777;
                }
            }
        }

        .btns {
            flex: 6;

            .add {
                background: radial-gradient(#FFDD57 0%, #FFA057 100%);
                border-radius: 35rpx 0rpx 0rpx 35rpx;
            }

            .buy {
                background: #FB4E47;
                // border-radius: 0rpx 35rpx 35rpx 0rpx;
                border-radius: 35rpx;
            }

            .btn-item {
                // width: 100%;
                // width: 220rpx;
                width: 450rpx;
                height: 70rpx;
                font-family: PingFang-SC, PingFang-SC;
                font-weight: 500;
                font-size: 30rpx;
                color: #FFFFFF;
            }
        }

    }

}

.wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 100%;

    .save {
        width: 284rpx;
        height: 66rpx;
        border-radius: 33rpx;
        border: 2rpx solid #FFFFFF;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: bold;
        font-size: 26rpx;
        color: #FFFFFF;
        margin-top: 40rpx;
    }

    .c {
        width: 512rpx;
        display: flex;
        justify-content: flex-end;
        margin-bottom: 20rpx;

        image {
            width: 46rpx;
            height: 46rpx;
        }
    }
}
</style>